<?php  
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
 
require_once("envoimoinscher.cfg.php");
?>
<?php
class envoimoinscher 
{
  public $classname = 'envoimoinscher';
  
  protected $_envs = array('TEST_ENV' => 'de test',
  'PROD_ENV' => 'de production',
  'LOCAL_ENV' => 'local');
  protected $_host = array('PROD_ENV' => 'https://www.envoimoinscher.com/',
  'TEST_ENV' => 'https://test.envoimoinscher.com/',
  'LOCAL_ENV' => 'http://localhost:8080/');
  protected $_mandatory = array('disponibilite.HDE', 'disponibilite.HLE', '', '', '');
  protected $_civilities = array('M' => 'M', 'Mlle' => 'Mlle', 'Mme' => 'Mme');
  protected $_delays = array('aucun' => 'le prix', 'minimum' => 'le délai');
  protected $_openers = array('la même fenêtre', 'une nouvelle popup');
  protected $_reasTransl = array("sale" => "vente", "repair" => "réparation", "return" => "retour", 
  "gift" => "cadeau, don", "sample" => "echantillon, maquette" , "personnal" => "usage personnel", 
  "document" => "documents inter-entreprises", "other" => "autre");
  protected $_types = array('colis' => 'colis', 'pli' => 'pli', 'encombrant' => 'encombrant', 'palette' => 'palette');
  protected $_hourStart = array('12:00' => '12:00', '12:15' => '12:15', '12:30' => '12:30', '12:45' => '12:45', '13:00' => '13:00', '13:15' => '13:15', '13:30' => '13:30', '13:45' => '13:45',
  '14:00' => '14:00', '14:15' => '14:15', '14:30' => '14:30', '14:45' => '14:45', '15:00' => '15:00', '15:15' => '15:15', '15:30' => '15:30', '15:45' => '15:45', '16:00' => '16:00', 
  '16:15' => '16:15', '16:30' => '16:30', '16:45' => '16:45', '17:00' => '17:00'); 
  protected $_hourEnd = array('17:00' => '17:00', '17:15' => '17:15', '17:30' => '17:30', '17:45' => '17:45', '18:00' => '18:00', '18:15' => '18:15', '18:30' => '18:30', '18:45' => '18:45',
  '19:00' => '19:00', '19:15' => '19:15', '19:30' => '19:30', '19:45' => '19:45', '20:00' => '20:00', '20:15' => '20:15', '20:30' => '20:30', '20:45' => '20:45', 
  '21:00' => '21:00');
  protected $_states = array('LIV' => 'Colis livré', 'ENV' => 'Colis envoyé', 'ANN' => 'Expédition annulée');
  protected $_specFields = array('select' => array('envoi.raison', 'disponibilite.HDE', 'disponibilite.HLE'),
  'separate' => array('proforma.description_fr', 'proforma.description_en')
  );
  protected $_tables = array('emc_categories', 'emc_dimensions', 'emc_configurations', 'emc_tracking', 'emc_documents', 'emc_points', 'emc_orders', 'emc_services', 'emc_operators');

  public function __construct()
  {
    $this->db =& new ps_DB;
    if($_GET['page'] == 'order.label_track')
    {
      $this->track((int)$_GET['order_id']);
      die();
    }
  }

  /**
   * Shows table with orders shipped by EnvoiMoinsCher services.
   * @access public
   * @return void
   */
  public function orders_table(&$d)
  {
    require_once( CLASSPATH .'htmlTools.class.php');
    require_once( CLASSPATH .'pageNavigation.class.php');
    if($_SESSION['send'])
    {
?>
      <div class="blockHelp">La commande de livraison a été correctement passée.</div>
<?php
      unset($_SESSION['send']);
    }
?> 
    <p class="big"><b>Les expéditions</b></p>
    <table class="adminlist" width="100%">
      <thead>
        <tr>
          <th>No</th>
          <th>Destinataire</th>
          <th>Date de <br />collecte prévue </th>
          <th>Date de <br />livraison prévue </th>
          <th>Statut</th>
          <th>Coût transport réel (TTC, €)</th>
          <th>Coût transport client (TTC, €)</th> 
          <th>Montant total de <br />la commande (TTC, €)</th> 
          <th>Référence EnvoiMoinsCher</th>
          <th>Transporteur <br />(Offre)</th>
          <th>Date commande <br />EnvoiMoinsCher</th>
          <th>Fiche commande</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
<?php
      // string with operators on rating mode
      $servicesCfg = explode(',',srvfrfo.','.srvintfo);
      foreach($servicesCfg as $service)
      {
        $servicesLike[] = "o.ship_method_id LIKE 'standard_shipping|".substr($service, 4, strlen($service))."%' ";
      }
      $whereLike = 'OR ('.implode(' OR ', $servicesLike).')';
      $page = (int)$_GET['page'];
      $queryCount = "SELECT COUNT(order_id) AS orders FROM #__{vm}_orders WHERE ship_method_id LIKE 'envoimoinscher|%' ".$whereLike."";
      $this->db->query($queryCount);
      $count = $this->db->loadAssocList();
      $pageNav = new vmPageNav($count[0]['orders'], $_GET['limitstart'], $_GET['limit']);
 
      $query = "SELECT o.*, eo.*, ui.first_name, ui.last_name, o.order_id AS main_id, os.order_status_name, ed.link_ed, DATE_FORMAT(eo.date_del_eo, '%d-%m-%Y %H:%i') AS dateDel, 
      DATE_FORMAT(eo.date_collect_eo, '%d-%m-%Y') AS dateCol, DATE_FORMAT(eo.date_del_eo, '%d-%m-%Y') AS dateDel, u.name, eop.name_eo,
      (UNIX_TIMESTAMP('".date("Y-m-d H:i:s")."') - UNIX_TIMESTAMP(eo.date_eo)) AS timeDifference
      FROM #__{vm}_orders o 
      JOIN #__{vm}_user_info ui ON ui.user_info_id = o.user_info_id
      JOIN #__{vm}_order_status os ON os.order_status_code = o.order_status
      JOIN #__users u ON u.id = o.user_id
	  LEFT JOIN emc_orders eo ON eo.order_id = o.order_id
      LEFT JOIN emc_documents ed ON ed.order_id = o.order_id AND ed.type_ed = 'label'
      LEFT JOIN emc_operators eop ON eop.code_eo = eo.operator_eo
      WHERE o.ship_method_id LIKE 'envoimoinscher|%' ".$whereLike."
      ORDER BY o.order_id DESC
	  LIMIT ".(int)$_GET['limitstart'].", ".(int)$_GET['limit']."";
      $this->db->query($query);
      $orders = $this->db->loadAssocList();
// print_r($orders);
      foreach($orders as $order)
      {
?>
        <tr>
          <td><?php echo $order['main_id'];?></td>
          <td><?php echo $order['last_name'];?> <?php echo $order['first_name'];?></td>
          <td><?php echo $order['dateCol'];?></td>
          <td><?php if($order['dateDel'] != '') { echo $order['dateDel']; } ?></td>
          <td><?php echo $order['order_status_name'];?></td>
          <td><?php echo $order['price_ttc_eo'];?></td>
          <td><?php echo (float)$order['order_shipping'];?></td>
          <td><?php echo (float)$order['order_total'];?></td>
          <td><?php echo $order['ref_eo'];?></td>
          <td><?php if($order['service_eo']  != '') { echo $order['name_eo']; ?> <br />(<?php echo $order['service_eo'];?>) <?php } else { ?>
          <?php $method = explode('|', $order['ship_method_id']); echo $method[1]; ?><br />(<?php echo $method[2];?>)
          <?php } ?></td>
          <td><?php echo date('d-m-Y H:i', $order['cdate']);?></td>
          <td><a href="index.php?page=order.order_print&limitstart=0&keyword=&order_id=<?php echo $order['main_id'];?>&option=com_virtuemart">voir</a></td>
          <td>
            <?php if($order['link_ed'] == '') { ?><a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=ship&order=<?php echo $order['main_id'];?>">expédier</a><?php }  
            elseif($order['link_ed'] != '' && $order['timeDifference'] <= 300) { ?>Bordereaux en cours de génération<?php } 
		    elseif($order['link_ed'] != '') { ?><a href="<?php echo $order['link_ed'];?>" target="_blank">télécharger <br />bordereau</a><?php } ?>
          </td>
        </tr>
<?php
      }
?>
      </tbody>
    </table>
    <table class="adminlist" width="100%">
      <thead><th>
<?php 
     echo $pageNav->getPagesLinks('index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=table');
?>
      </th></tbody>
    </table>
<?php
  }

  /** 
   * Displays form for order the EnvoiMoinsChers' shipping service.
   * @access public
   * @return void
   */
  public function ship_order()
  { 
    $orderId = (int)$_GET['order'];
    $order = $this->prepareOrderInfo($orderId); 
// print_r($order['method']);
// print_r($order['package']);
// print_r($order['delivery']);die();
// print_r($order['method']);
    require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
    require_once(CLASSPATH ."shipping/envoimoinscher/WebService.php");
    require_once(CLASSPATH ."shipping/envoimoinscher/Quotation.php");
    // API call to find offer
    $cotCl = new Env_Quotation(array("user" => logemc, "pass" => mdpemc, "key" => apiemc));  
    $from = array("pays" => "FR", "code_postal" => zipcod, "ville" => citnam, "type" => "entreprise", 
    "adresse" => addexp, 'prenom' => fsname, 'nom' => lsname, 'civilite' => civexp,
    'email' => addmai);
  
    $quotInfo = array("collecte" => $this->setDate(date('Y-m-d'), (pickup*(24*60*60)), 'Y-m-d'), 
    "delai" => delai, 'description' => colis_description,
    "code_contenu" => nature, 'valeur' => (float)$order['order_total'] );
    $cotCl->server = $this->getHost(envs);
    $cotCl->setPerson("expediteur", $from);

    $cotCl->setPerson("destinataire", array("pays" => $order['delivery']['country'], 
    "code_postal" => $order['delivery']['zip'] , 
    "ville" => $order['delivery']['city'], 
    "type" => "particulier", 
    "adresse" => urlencode($order['delivery']['address']),
    'nom' => $order['delivery']['last_name'], 'prenom' => $order['delivery']['first_name'],
    'civilite' => 'M', 'email' => $order['delivery']['email'], 'tel' => $order['delivery']['phone_1']
    )); 
    $cotCl->setType(typesend, $order['package']);
 
    // set pro forma
    if(count($order['proforma']) > 0)
    {
      $cotCl->setProforma($order['proforma']);
    }
    $cotCl->getQuotation($quotInfo); 
    $cotCl->getOffers(false);
    $offersCnt = array();
    foreach($cotCl->offers as $o => $offer)
    {
      $uniqCode = $offer['operator']['code'].$offer['service']['code'];
      $offersCnt[$uniqCode]++;
      if($offer['operator']['code'] == trim($order['method'][1]) && $offer['service']['code'] == trim($order['method'][2]))
      {
        $choosenOffer = $offer;
        if($offersCnt[$uniqCode] == $order['method'][4] || $order['method'][4] == '')
        {
          break;
        }
      } 
    }
    define('colis_valeur', $order['order']['order_subtotal']);

    // get config to know which type of fields we have to show
    $this->db->query("SELECT * FROM emc_configurations ORDER BY order_ec ASC");
    $configurations = $this->db->loadAssocList();
    $outputConf = array();
    foreach($configurations as $config)
    {
      $outputConf[$config['key_ec']] = $config;
    }
// print_r($choosenOffer);
    if(count($choosenOffer) <= 0)
    {
      $offersWanted = explode(',', srvfrre);
      $offerWantedFo = explode(',', srvfrfo);
      if($order['delivery']['country'] != 'FR')
      {
        $offersWanted = explode(',', srvintre);
        $offerWantedFo = explode(',', srvintfo);
      }
      $offersAccepted = array_merge($offersWanted, $offerWantedFo);
?>
    <div class="blockHelp" style="margin-bottom:20px;">
    L'offre choisie par votre client n'est plus disponible. Vous pouvez en sélectionner une nouvelle (prévenez votre client du changement de l'offre) ou réessayer plus tard.
    </div>
    <p><b>L'offre sélectionnée par le client : </b> <?php echo $order['method'][2];?> (<?php echo $order['method'][1];?>) </p>
    <p><b>Les nouvelles offres</b></p>
    <table class="formEmc">
      <thead>
        <tr>
          <td>Transporteur</td>
          <td>Service</td>
          <td>Prix HT</td>
          <td>Prix TTC</td>
          <td>Prix facturé<br />au client TTC</td>
          <td>Date de collecte</td>
          <td>Date de livraison</td>
          <td></td>
        </tr>
      </thead>
      <tbody>
<?php foreach($cotCl->offers as $o => $offer) {
        $uniqCode = $offer['operator']['code'].$offer['service']['code'];
        (int)$quantOffer[$uniqCode]++;
        $offerNb = '';
        if($quantOffer[$uniqCode] > 1)
        {
          $offerNb = '|'.$quantOffer[$uniqCode];
        }
        if(in_array($uniqCode, $offersAccepted)) {
?>
        <tr>
          <td><?php echo $offer['operator']['label'];?></td>
          <td><?php echo $offer['service']['label'];?></td>
          <td><?php echo $offer['price']['tax-exclusive'];?>&nbsp;€ </td>
          <td><?php echo $offer['price']['tax-inclusive'];?>&nbsp;€</td>
          <td><?php echo $order['order_shipping'];?>&nbsp;€</td>
          <td><?php echo date('d-m-Y', strtotime($offer['collection']['date']));?></td>
          <td><?php echo date('d-m-Y', strtotime($offer['delivery']['date']));?></td>
          <td><a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=replace&order=<?php echo $orderId;?>&srv=<?php echo $offer['service']['code'];?>&ope=<?php echo $offer['operator']['code'];?>&price=<?php echo $offer['price']['tax-inclusive'];?>&nb=<?php echo $offerNb;?>" style="font-size:10px;">remplacer par cette offre</a></td>
        </tr>
<?php 
        }
      } ?>
      </tbody>
    </table>
<?php 
    } 
    else 
    {
?>
  <script type="text/javascript"> 
    window.addEvent('domready', function() {
      var elements = document.getElementsByName('task');
      for(var i = 0; i < elements.length; i++)
      {
        elements[i].value = "sendShip";
      }
      var saveBtn = $$('#toolbar table tbody tr td');
      for(var j = 0; j < saveBtn.length; j++) 
      {
        var oldContent = saveBtn[j].innerHTML;
        // only when innerHTML contains "vmicon-32-save"
        if(oldContent.indexOf("vmicon-32-save") != -1) 
        {
          var newContent = oldContent.replace(/Save/g, 'Expédier'); 
          saveBtn[j].innerHTML = newContent;
        }
      }
    });
  </script>
<?php if($_SESSION['problem']) { ?>
  <div class="blockHelp" style="margin-bottom:20px;">Un problème est survenu lors de l'expédition de la commande : <br />
    <?php echo $_SESSION['errors'];?>
    <?php unset($_SESSION['problem']); unset($_SESSION['errors']); ?>
  </div>
<?php } ?>
  <div style="width:400px; float:left; margin-right:10px;">
    <table class="formEmc">
      <thead>
        <tr>
          <td>Transporteur</td>
          <td>Service</td>
          <td>Prix HT</td>
          <td>Prix TTC</td>
          <td>Date de collecte</td>
          <td>Date de livraison</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><?php echo $choosenOffer['operator']['label'];?></td>
          <td><?php echo $choosenOffer['service']['label'];?></td>
          <td><?php echo $choosenOffer['price']['tax-exclusive'];?>&nbsp;€ </td>
          <td><?php echo $choosenOffer['price']['tax-inclusive'];?>&nbsp;€</td>
          <td><?php echo date('d-m-Y', strtotime($choosenOffer['collection']['date']));?></td>
          <td><?php echo date('d-m-Y', strtotime($choosenOffer['delivery']['date']));?></td>
        </tr>
      </tbody>
    </table>
    <?php } ?>
    <p><b>Destinataire</b></p>
    <table class="formEmc">
      <thead>
        <tr>
          <td>Nom Prénom</td>
          <td>Adresse</td>
          <td>Ville</td>
          <td>Adresse e-mail</td>
          <td>Numéro de téléphone</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><?php echo $order['delivery']['last_name'];?> <?php echo $order['delivery']['first_name'];?></td>
          <td><?php echo $order['delivery']['address'];?></td>
          <td><?php echo $order['delivery']['zip'];?> <?php echo $order['delivery']['city'];?></td>
          <td><?php echo $order['delivery']['email'];?></td>
          <td><?php echo $order['delivery']['phone_1'];?></td>
        </tr>
      </tbody>
    </table>
  </div>
  <?php
  if(count($choosenOffer) > 0)
  {
    // if parcel point for dropoff demanded, make new constat 
    if($order['parcelPoint'] != '')
    {
      $pt = substr($order['parcelPoint'], 5, strlen($order['parcelPoint']));
      define('retrait_pointrelais', $pt); 
    }
  ?>
  <div style="width:400px; float:left;">
    <p><b>Informations obligatoires à fournir</b></p>
    <?php unset($choosenOffer['mandatory']['proforma.poids']); unset($choosenOffer['mandatory']['proforma.nombre']);
	unset($choosenOffer['mandatory']['poforma.description_fr']); unset($choosenOffer['mandatory']['poforma.description_en']); 
	unset($choosenOffer['mandatory']['proforma.valeur']); unset($choosenOffer['mandatory']['proforma.origine']);
    // For Chronopost we don't need to choose the parcel point (even if the API demands)
	if($choosenOffer['mandatory']['depot.pointrelais']['array'][0] == 'SERN-POST') 
    {
?>
      <input type="hidden" name="depot.pointrelais" id="depot.pointrelais" value="<?php echo $choosenOffer['mandatory']['depot.pointrelais']['array'][0];?>" />
<?php
      unset($choosenOffer['mandatory']['depot.pointrelais']);
    }
    foreach($choosenOffer['mandatory'] as $m => $mandatory) { ?>
        <?php if(!in_array($mandatory['code'], $this->_specFields['separate']) && !in_array($mandatory['code'], $this->_specFields['select'])
		&& (count($mandatory['array']) == 0 || (count($mandatory['array'])  > 0 && strpos('pointrelais', $mandatory['code']) === FALSE))) { ?>
		<p><label for="mandat_<?php echo $mandatory['code'];?>"><?php echo $mandatory['label'];  ?></label> 
		<input type="text" id="mandat_<?php echo $mandatory['code'];?>" name="<?php echo $mandatory['code'];?>" value="<?php echo constant(str_replace('.', '_', $mandatory['code']));?>" /></p>
        <?php } elseif(in_array($mandatory['code'], $this->_specFields['select'])) { ?>
		  <p><label for="mandat_<?php echo $mandatory['code'];?>"><?php echo $mandatory['label'];  ?></label> 
          <?php $codeRepl = str_replace('.', '_', $mandatory['code']); $str = "get".$codeRepl; echo make_select($mandatory['code'], $this->$str(), '', constant($codeRepl)); ?></p>
        <?php } ?>
    <?php } ?> 
      <p><label for="mandat_date">Date de collecte</label> <input type="text" id="mandat_date" name="collecte" value="<?php echo $choosenOffer['collection']['date'];?>" />
      <br /><b><small>format : YYYY-MM-DD; exemple pour 30 décembre 2000 : 2000-12-30</small></b></p>
    <?php if(count($order['proforma']) > 0 && count($choosenOffer['mandatory']['proforma.description_en']) > 0) { ?>
      <p><b>Informations sur les objets envoyés</b></p>
      <table><tr>
      <?php foreach($order['proforma'] as $l => $line) { ?> 

        <td><p><b>Objet #<?php echo $l;?></b></p>
        <p><input type="text" name="desc_fr_<?php echo $l;?>" id="desc_fr_<?php echo $l;?>" value="<?php echo $line['description_fr'];?>" /> <small>(en français)</small></p>
        <p><input type="text" name="desc_en_<?php echo $l;?>" id="desc_en_<?php echo $l;?>" value="<?php echo $line['description_en'];?>" /> <small>(en anglais)</small></p> </td>
      <?php } ?>
      </tr></table>
    <?php } ?>
  </div>
  <input type="hidden" name="exec" value="sendShip" />
  <input type="hidden" name="order" value="<?php echo $orderId;?>" />
<?php 
       
    }
  }

  /**
   * Replaces old shippment offer by another one.
   * @access public
   * @return void
   */
  public function replace()
  {
    $orderId = (int)$_GET['order'];
    $price = (float)$_GET['price'];
    $newCode = $this->classname."|".$_GET['ope']."|".$_GET['srv']."|".number_format($price,2).$_GET['nb'];
    $this->db->query("UPDATE #__{vm}_orders SET 
    order_shipping  = '".$price."',
    ship_method_id = '".$newCode."'
    WHERE order_id = ".$orderId." ");
    Header("Location: index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=ship&order=".$orderId."");
    die();
  }

  /**
   * Makes cotation of EnvoiMoinsCher.com offers.
   * @access public
   * @return void
   */
  public function list_rates(&$d) 
  {
    global $CURRENCY_DISPLAY, $GLOBALS;
    require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
    require_once(CLASSPATH ."shipping/envoimoinscher/WebService.php");
    require_once(CLASSPATH ."shipping/envoimoinscher/Quotation.php"); 
    require_once(CLASSPATH ."shipping/standard_shipping.php");

    $offresPresented = array();
    // get delivery address
    $q = "SELECT * FROM #__{vm}_user_info, #__{vm}_country WHERE user_info_id='" . $d["ship_to_info_id"]."' AND ( country=country_2_code OR country=country_3_code)";
    $this->db->query($q);
    $delivery = $this->db->loadAssocList();

    $addressDest = $delivery[0]['address_1'];
    if($delivery[0]['address_2'] != '')
    {
      $addressDest = implode('|', array($delivery[0]['address_1'],$delivery[0]['address_2']));
    }
    // FX => FR conversion
    if($delivery[0]['country_2_code'] == 'FX' || $delivery[0]['country_2_code'] == 'FXX')
    {
      $delivery[0]['country_2_code'] = 'FR';
    }
    $offersWanted = explode(',', srvfrre);
    $offerWantedFo = explode(',', srvfrfo);
    if($delivery[0]['country_2_code'] != 'FR')
    {
      $offersWanted = explode(',', srvintre);
      $offerWantedFo = explode(',', srvintfo);
    } 
    $qDim = "SELECT length_ed, width_ed, height_ed FROM emc_dimensions WHERE weight_from_ed < ".(float)$d['weight']." AND 
    weight_ed >= ".(float)$d['weight']." ";
    $this->db->query($qDim);
    $dimensions = $this->db->loadAssocList();

    // before APIs' call, be sure to remove all shipping rates    
    $stClass = new standard_shipping;
    $query = "SELECT * FROM #__{vm}_shipping_carrier sc 
    JOIN #__{vm}_shipping_rate sr ON sr.shipping_rate_carrier_id = sc.shipping_carrier_id
    WHERE sc.is_emc = 1 AND sr.shipping_rate_weight_start <= ".$d["weight"]." AND 
    sr.shipping_rate_weight_end >= ".$d["weight"]." AND
    (shipping_rate_country LIKE '%".$delivery[0]['country_3_code']."%' OR shipping_rate_country = '')";
    $this->db->query($query);
    $carriers = $this->db->loadAssocList();
    echo '<script type="text/javascript">
    window.onload = function() {
    ';
    $shipsIds = array();
    foreach($carriers as $c => $carrier)
    {
      $shipsIds[] = $carrier['emc_code'];
      echo 'var oP = document.getElementById("shipping_rate_id_ss_'.$carrier['shipping_rate_id'].'");
      var parentTd = oP.parentNode;
      parentTd.parentNode.innerHTML = ""; ';
    }
    echo '} ; </script>';

    $cotCl = new Env_Quotation(array("user" => logemc, "pass" => mdpemc, "key" => apiemc));  
    $from = array("pays" => "FR", "code_postal" => zipcod, "ville" => citnam, "type" => "entreprise", "adresse" => addexp);
  
    $quotInfo = array("collecte" => $this->setDate(date('Y-m-d'), (pickup*(24*60*60)), 'Y-m-d'), 
    "delai" => delai, 'valeur' => (float)$GLOBALS['total'],
    "code_contenu" => nature);
    $cotCl->server = $this->getHost(envs);
    $cotCl->setPerson("expediteur", $from); 
    $cotCl->setPerson("destinataire", array("pays" => $delivery[0]['country_2_code'], 
    "code_postal" => $delivery[0]['zip'] , 
    "ville" => $delivery[0]['city'] , 
    "type" => "particulier", 
    "adresse" => $addressDest));
    $cotCl->setType(typesend, array(1 => array("poids" => (float)$d['weight'], "longueur" => $dimensions[0]['length_ed'], 
    "largeur" => $dimensions[0]['width_ed'], "hauteur" => $dimensions[0]['height_ed'])));
    $cotCl->getQuotation($quotInfo);
    if(!$cotCl->curlError && !$cotCl->respError)
    {
      // if parcel point wasn't choosen
      if($_SESSION['choose_parcel'] == true)
      {
        echo '<div class="shop_error"><b>Erreur</b>: Veuillez sélectionner le point relais.<br></div>';
      }
      $cotCl->getOffers(false);
      foreach($cotCl->offers as $o => $offer)
      {
        $offerCode = $offer['operator']['code'].$offer['service']['code'];
        // check if offer is desired by user (configuration)
        if(in_array($offerCode, $offersWanted) && !in_array($offerCode, $offresPresented))
        {
          // THE ORDER OF THOSE VALUES IS IMPORTANT:
          // ShippingClassName|carrier_name|rate_name|totalshippingcosts|rate_id
          $shipping_rate_id = urlencode($this->classname."|".$offer['operator']['label']."|".$offer['service']['code']."|".number_format($offer['price']['tax-inclusive'],2));

          if($_SESSION['choose_parcel'] == true && $offer['operator']['code'] == 'SOGP')
          {
            echo '<script type="text/javascript">
            window.onload = function() {
              document.getElementById("ship_'.$o.'").checked = true;
            }
            </script>';
            unset($_SESSION['choose_parcel']);
          }
          $html = '<input type="radio" name="shipping_rate_id" id="ship_'.$o.'" value="'.$shipping_rate_id.'" />
          <label for="ship_'.$o.'">'.$offer['service']['label'].' ('.$offer['operator']['label'].'): '.$offer['price']['tax-inclusive'].' € TTC
          </label>';
          if($offer['delivery']['type'] == 'PICKUP_POINT')
          { 
            $html .= makeMap(implode('|',$offer['mandatory']['retrait.pointrelais']['array']), true);
            // for instance, only Relais Colis
            $html .= '<script type="text/javascript">var relaisColisId = "ship_'.$o.'";</script>';
          }
          $html .= '<br />';
          $_SESSION[$shipping_rate_id] = 1;
          echo $html;
          $offresPresented[] = $offerCode; 
          unset($cotCl->offers[$o]);
        }
        elseif(in_array($offerCode, $offresPresented))
        { 
          unset($cotCl->offers[$o]);
        }
      }
      // shipping rate prices (coppied from standard_shipping.php)
      if(count($offerWantedFo) > 0)
      {
        foreach($cotCl->offers as $o => $offer)
        {
          $code = $offer['operator']['code'].$offer['service']['code'];
          if(in_array($code, (array)$offerWantedFo) && in_array($code, (array)$shipsIds) && !in_array($code,(array)$used))
          {
            $key = array_keys($shipsIds, $code);
            $carrier = $carriers[$key[0]];
            if($_SESSION['auth']['show_price_including_tax'] != 1)
            {
              $taxrate = 1;
            }
            else
            {
              $taxrate = $stClass->get_tax_rate($carrier["shipping_rate_id"]) + 1;
            }
            $from = array('&euro;', '€');
            $to = array('', '');
            $total_shipping_handling = $carrier["shipping_rate_value"] + $carrier["shipping_rate_package_fee"];
            $total_shipping_handling = $GLOBALS['CURRENCY']->convert($total_shipping_handling, $shipping_rate_currency_code, $GLOBALS['product_currency']);
            $total_shipping_handling *= $taxrate ;
            $show_shipping_handling = $CURRENCY_DISPLAY->getFullValue($total_shipping_handling);
            $shipping_rate_id = urlencode($this->classname."|".$offer['operator']['label']."|".$offer['service']['code']."|".number_format($total_shipping_handling,2));
            $html = '<input type="radio" name="shipping_rate_id" id="ship_'.$o.'" value="'.$shipping_rate_id.'" />
            <label for="ship_'.$o.'">'.$offer['service']['label'].' ('.$offer['operator']['label'].'): '.str_replace($from, $to, $show_shipping_handling).' € TTC
            </label>';
      	    if($offer['delivery']['type'] == 'PICKUP_POINT')
      	    {
              $html .= makeMap(implode('|',$offer['mandatory']['retrait.pointrelais']['array']), true);
              // for instance, only Relais Colis
              $html .= '<script type="text/javascript">var relaisColisId = "ship_'.$o.'";</script>';
      	    }
            echo $html.'<br />';
            $used[] = $code;
            $_SESSION[$shipping_rate_id] = 1;
          }
        }
      }
    }
    else
    {
      echo '<div class="shop_error">'.msgerror.'</div>';
    }
    return true;
  }

  public function get_rate_details(&$d) 
  { 
    echo 'get_rate_details';  
  }


  public function get_rate(&$d) 
  {
    if($_POST['point'] != '')
    {
      $_SESSION['point'] = $_POST['point'];
    }
    $shipping_rate_id = $d["shipping_rate_id"];
    $is_arr = explode("|", urldecode(urldecode($shipping_rate_id)) );
    $order_shipping = $is_arr[3];
    return $order_shipping;
  }

  public function get_tax_rate($shipping_rate_id = 0) 
  {
 
  }

  /**
   * Checks if shipping method exists in the session.
   */
  public function validate(&$d) 
  {
    $shipping_rate_id = $d["shipping_rate_id"];
    if(array_key_exists($shipping_rate_id, $_SESSION)) 
    {
      unset($_SESSION['choose_parcel']);
      if($_POST['checkout_this_step'][0] == 'CHECK_OUT_GET_SHIPPING_METHOD')
      {
        // check if parcel points was choosen (todo : detection more general)
        if(strpos($shipping_rate_id, 'RelaisColis') !== false)
        {
          if(!preg_match('/^[A-Z]{4}-([A-Za-z0-9]+)$/', $_POST['point']))
          {
            $_SESSION['choose_parcel'] = true;
            $shipInfoId = $_POST['ship_to_info_id'];
            if(!ctype_alnum($shipInfoId))
            {
              $shipInfoId = '';
            }
            // we have to do it manually (VM redirects by HTTP_REFERER and if last page that I visited is emc_parcelpoints.list.php, I'm redirected here, 
            // and not to page with ship methods)
            Header("Location: index.php?page=checkout.index&option=com_virtuemart&ship_to_info_id=".$shipInfoId."&shipping_rate_id=".urlencode($shipping_rate_id)."&checkout_stage=2&Itemid=1");
            return false;
          }
          else 
          {
            return true;
          }
        }
      }
      return true;
    }
    else
    {
      return false;
    }
  }

  /**
   * Save informations about choosen shippment method (used only to save parcel point choosen by user).
   * @access public
   * @return void
   */
  public function save_rate_info(&$d)
  {
    $shipping_rate_id = $d['shipping_rate_id'];
    $db =& JFactory::getDBO(); //Returns a reference to the global database object
    $prefix = $db->getPrefix();
    if(preg_match('/^[A-Z]{4}-([A-Za-z0-9]+)$/', $_SESSION['point']))
    {
      $ope = explode('-', $_SESSION['point']);
      $insert = "INSERT INTO emc_points (order_id, point_ep, emc_operators_code_eo) VALUES
      ('".$d['order_id']."', '".$_SESSION['point']."', '".trim($ope[0])."')";
      $this->db->query($insert);
    }
  }

  public function rate_id_valid($rate_id, $country, $zip, $weight) 
  {
    echo 'rate_id_valid'; 
  }

  /**
   * Shows shipping configuration. 
   * We want to avoid to show a form with 300 lines. It's why we save some configuration view data 
   * in the database (emc_configurations).
   * But we save the values normally, in envoimoinscher.cfg.php, as the constants.
   * @return void
   */
  public function show_configuration() 
  {
    if($_GET['act'] == '' || $_GET['act'] == 'config')
    {
      $this->backendStyles(array('config' => 'text-decoration:underline;'), true);
      if(defined("emcIsInstalled")) 
      {
        // get configuration informations and labels
        $this->db->query("SELECT * FROM emc_configurations ORDER BY order_ec ASC");
        $configurations = $this->db->loadAssocList(); 
?>
        <script type="text/javascript">
        function openPopupEmc()
        {
          window.open("http://www.envoimoinscher.com/magento_rc.html?fcp=&fadr=&fvil=&TypeLiv=REL&type=Exp&isVirtuemart=true","emcwindow","scrollbars=1, resizable=1,width=650,height=680");
        }
        </script>
        <div class="formEmc">
        <p class="big"><b>La configuration</b></p>
        <div class="blockHelp">Contactez EnvoiMoinsCher pour une aide sur le choix des offres.</div>
<?php
        if($_SESSION['updated'])
        {
?>
        <div class="blockHelp" style="margin-top:20px;"><b>La configuration a été mise à jour.</b></div>
<?php  
          unset($_SESSION['updated']);
        }

        if($_SESSION['installOk'] == 1)
        {
?>
         <div class="blockHelp" style="margin-top:20px; color: green;"><b>L'installation s'est déroulée avec succès. Veuillez configurer le module.</b></div>
<?php
          unset($_SESSION['installOk']);
        }

        // notify user about api connection problem (wrong credentials probably)
        if(apiConnectionError == 1)
        {
?>
        <div class="blockHelp" style="margin-top:20px;"><b>! Veuillez vérifier si vos identifiants de connexion à l'API sont corrects.</b></div>
<?php
        }

        // if first launch
        if(!defined(wasLaunched) || wasLaunched == 0)
        {
          $query = "SELECT * FROM #__{vm}_vendor LIMIT 1";
          $this->db->query($query);
          $vendor = $this->db->loadAssocList();
          define('lsname', $vendor[0]['contact_last_name']);
          define('fsname', $vendor[0]['contact_first_name']);
          define('civexp', $vendor[0]['contact_title']);
          define('numtel', $vendor[0]['contact_phone_1']);
          define('addmai', $vendor[0]['contact_email']);
          define('addexp', $vendor[0]['vendor_address_1'].$vendor[0]['vendor_address_2']);
          define('citnam', $vendor[0]['vendor_city']);
          define('zipcod', $vendor[0]['vendor_zip']);
          define('societe', $vendor[0]['vendor_store_name']);
        }

        foreach($configurations as $c => $config)
        {
          $additional = (array)unserialize($config['html_ec']); //print_r($additional);
          if($config['key_ec'] == 'srvintre') { echo '<br />'; }
?> 
        <p><label for="config-<?php echo $config['key_ec'];?>"><?php echo $config['label_ec'];?></label>
          <?php if($additional['type'] != '') {
            $function = "make_".$additional['type'];
            $items = "";
            $source = explode('/', $additional['source']);
            if($source[0] == 'this') 
            {  
              $items = $this->$source[1]();
            }
            echo $function("config-".$config['key_ec'], $items, $additional['default'], constant(str_replace('.', '_', $config['key_ec']))); 
          } else { ?>
          <input type="text" name="config-<?php echo $config['key_ec'];?>" id="config-<?php echo $config['key_ec'];?>" value="<?php echo constant(str_replace('.', '_', $config['key_ec']));?>" />
          <?php } ?>
          <?php if($additional['notice'] != '') { ?>
          <small><b><?php echo html_entity_decode($additional['notice']);?></b></small>
          <?php } ?>
        </p>
    <?php } ?> 
      </div><!-- formEmc-->  
<?php
      }
      else 
      {
        // install page
?>
       <p>Afin d'utiliser le module, veuillez <a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=install">l'installer</a></p>.
<?php
      }
    }
    elseif($_GET['act'] == 'table') 
    {
      $this->backendStyles(array('cmd' => 'text-decoration:underline;', true));
      $this->orders_table();
    }
    elseif($_GET['act'] == 'ship') 
    {
      $this->backendStyles(array('cmd' => 'text-decoration:underline;', true));
      $this->ship_order();
    }
    elseif($_GET['act'] == 'replace') 
    {
      $this->backendStyles(array());
      $this->replace();
    }
    elseif($_GET['act'] == 'install') 
    {
      $this->backendStyles(array('install' => 'text-decoration:underline;', true));
      $this->install();
    }
    elseif($_GET['act'] == 'update') 
    {
      $this->backendStyles(array('update' => 'text-decoration:underline;', true));
      $this->update();
    }
    elseif($_GET['act'] == 'uninstall') 
    {
      $this->backendStyles(array('uninstall' => 'text-decoration:underline;', true));
      $this->uninstall();
    }
  }

  /** 
   * Saves informations about the configuration (access, parcel points, address...)
   * @return void
   */
  public function write_configuration()
  {
    $this->backendStyles();
    if($_POST['exec'] == 'sendShip')
    {
      $this->sendEmcOrder($_POST);
      $_SESSION['send'] = true;
      Header("Location: index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=table&limit=50&limitstart=0");
    }
    else
    {
      $separate = array('config-srvfrre', 'config-srvintre', 'config-srvfrfo', 'config-srvintfo');
      $configTxt = "<?php if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' ); ";
      $configTxt .= " \n ";
      foreach($_POST as $key => $post)
      {
        if(strpos($key, 'config-') !== false && !in_array($key, $separate))
        {
          $configTxt .= "define('".str_replace('config-', '', $key)."', '".addslashes($post)."'); \n ";
        }
        elseif(in_array($key, $separate))
        {
          $configTxt .= "define('".str_replace('config-', '', $key)."', '".implode(',',$_POST[$key])."'); \n ";
        }
      }
      // always check the credentials and notify user if they aren't valid
      $options = array(CURLOPT_URL => $this->getHost($_POST['config-envs'])."/verifier_utilisateur.html", CURLOPT_POST => true,
      CURLOPT_POSTFIELDS => http_build_query(array('login' => $_POST['config-logemc'], 'key' => $_POST['config-apiemc'], 
      'store' => $_SERVER['HTTP_HOST'], 'platform' => 'Virtuemart', 'tested' => date('Y-m-d H:i:s'))), CURLOPT_RETURNTRANSFER => 1);
      $options[CURLOPT_SSL_VERIFYPEER] = false; 
      $options[CURLOPT_SSL_VERIFYHOST] = 0;
      $req = curl_init();
      curl_setopt_array($req, $options);
      $result = curl_exec($req);
      curl_close($req);
      if(trim($result) != 1)
      {
        // api connection problem was detected (wrong credentials) 
        $configTxt .= "define('apiConnectionError', 1); \n";
      }
      else
      {
        $configTxt .= "define('apiConnectionError', 0); \n";
      }
      $configTxt .= "define('emcIsInstalled', 1); \n";
      $configTxt .= "?>";
      file_put_contents(CLASSPATH.'shipping/envoimoinscher.cfg.php', $configTxt); 
      // handle shippers management
      // all available services
      $query = "SELECT * FROM emc_operators ORDER BY id_eo ASC";
      $this->db->query($query);
      $operatorsDb = $this->createOpeArray($this->db->loadAssocList());
      // all services from POST request
      $allServFr = (array)$_POST['config-srvfrfo'];
      $allServIn = (array)$_POST['config-srvintfo'];
      $allServices = array_merge($allServFr, $allServIn);
      // $allServices = array_unique($allServices);
      $query = "SELECT * FROM #__{vm}_shipping_carrier sc 
      JOIN #__{vm}_shipping_rate sr ON sr.shipping_rate_carrier_id = sc.shipping_carrier_id 
      WHERE sc.is_emc = 1";
      $this->db->query($query);
      $services = $this->db->loadAssocList();
      // services already in the database
      foreach($services as $service)
      {
        if(in_array($service['emc_code'], $allServices))
        {
          // do not remove service which is used (has shipping rate) and is defined in POST request
          $notInCode[] = "'".$service['emc_code']."'";
        }
        else 
        {
          // remove services from the database which are not defined in POST request
          $inId[] = $service['shipping_carrier_id'];
        }
      }
      if(count($notInCode) > 0)
      {
        $where = "AND emc_code NOT IN (".implode(',', $notInCode).")";
      }
      $removeQuery = "DELETE FROM #__{vm}_shipping_carrier WHERE is_emc = 1 $where";
      $this->db->query($removeQuery);  
      if(count($inId) > 0)
      {
        $removeQuery = "DELETE FROM #__{vm}_shipping_rate WHERE shipping_rate_carrier_id IN (".implode(',', $inId).")";
        $this->db->query($removeQuery);
      }
      // create new services
      foreach($allServices as $s => $service)
      {
        $suffix = ', national';echo $service;
        if(in_array($service, $allServIn) && !in_array($service, $allServFr))
        {
          $suffix = ', international';
          $keys = array_keys($allServIn, $service);
          unset($allServIn[$keys[0]]);
        }
        else
        {
          $keys = array_keys($allServFr, $service);
          unset($allServFr[$keys[0]]);
        }
        if(!in_array("'".$service."'", (array)$notInCode))
        {
          $expr = substr($service, 4, strlen($service));
          $expr .= ' ('.$operatorsDb[substr($service, 0, 4)]['name_eo'].'';
          $query = "INSERT INTO #__{vm}_shipping_carrier (shipping_carrier_name, is_emc, emc_code, emc_name) 
          VALUES ('".$expr." ".$suffix.")', 1, '".$service."', '".$expr.")')";
          $this->db->query($query);
        }
      }
      $_SESSION['updated'] = true;
      Header("Location: index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart");
      die();
    }
  }

  private function sendEmcOrder($post)
  {
    $orderId = (int)$post['order'];
    $order = $this->prepareOrderInfo($orderId); 
    $post['codeOrder'] = sha1($orderId.time().rand(0, 9999));

    require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
    require_once(CLASSPATH ."shipping/envoimoinscher/WebService.php");
    require_once(CLASSPATH ."shipping/envoimoinscher/Quotation.php");
    // API call to find offer
    $cotCl = new Env_Quotation(array("user" => logemc, "pass" => mdpemc, "key" => apiemc));  
    $from = array("pays" => "FR", "code_postal" => zipcod, "ville" => citnam, 
      "type" => "entreprise", "adresse" => addexp, "infos" => cominf,
      'prenom' => fsname, 'nom' => lsname, 'civilite' => civexp,
      'email' => addmai, 'tel' => numtel, 'societe' => societe
    );

    $quotInfo = array("collecte" => date('Y-m-d', strtotime($post['collecte'])),
      "delai" => delai, "operateur" => $order['method'][1], "service" => $order['method'][2], 
      "assurance.selection" => "off",  
	  "code_contenu" => nature, 
	  "url_tracking" => 'http://'.$_SERVER['HTTP_HOST'].'/index.php?page=emc_tracking.put&option=com_virtuemart&code='.$post['codeOrder']
    );
    $cotCl->server = $this->getHost(envs);
    $cotCl->setPerson("expediteur", $from); 
    $cotCl->setPerson("destinataire", array("pays" => $order['delivery']['country'], 
      "code_postal" => $order['delivery']['zip'] , 
      "ville" => $order['delivery']['city'], 
      "type" => "particulier", 
      "adresse" => $order['delivery']['address'],
      'nom' => $order['delivery']['last_name'], 'prenom' => $order['delivery']['first_name'],
      'civilite' => 'M', 'email' => $order['delivery']['email'], 'tel' => $order['delivery']['phone_1']
    ));
    $cotCl->setType(typesend, $order['package']);
    foreach($post as $p => $line)
    {
      if(strpos($p, 'pointrelais') !== false)
      {
        $line = $order['method'][1]."-".$line;
      }
      $quotInfo[str_replace('_', '.', $p)] = $line;
    } 
    $quotInfo['description'] = $quotInfo[typesend.'.description']; 
    $quotInfo['valeur'] = $quotInfo[typesend.'.valeur']; 
    // if proforma
    if(count($order['proforma'] > 0))
    { 
      foreach($order['proforma'] as $p => $proforma)
      {
        $order['proforma'][$p]['description_fr'] = $post['desc_fr_'.$p];
        $order['proforma'][$p]['description_en'] = $post['desc_en_'.$p]; 
      }
      $quotInfo['raison'] = $post['envoi_raison'];
    }
    $cotCl->setProforma($order['proforma']);
    $orderPassed = $cotCl->makeOrder($quotInfo, true);
    if(!$cotCl->curlError && !$cotCl->respError && $orderPassed) 
    {
      $this->insertEmcOrder($orderId, $cotCl->order, $post);
    }
    else
    {
      $errors = array();
      foreach((array)$cotCl->respErrorsList as $e => $error)
      {
        $errors[] = '<b>'.$error['message'].'</b>';
      }
      $_SESSION['problem'] = 1;
      $_SESSION['errors'] = implode(', ', $errors).'<br /><br />'.$cotCl->curlErrorText;
      Header("Location: index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=ship&order=".$orderId."");
      die();
    }
  }

  public function shippingmethodSave() 
  {  
  }

  public function configfile_writeable() {
    return is_writeable( CLASSPATH."shipping/".$this->classname.".cfg.php" );
  }

  /**
   * Getter used to tracking state.
   * @return array
   */
  public function getTrackingLabel($key)
  {
    return $this->_states[$key];
  }

  /**
   * Getter used to display the civilities.
   * @return array
   */
  private function getCivilities()
  {
    return $this->_civilities;
  }

  /**
   * Getter used to display categories.
   * @return array
   */
  private function getCategories()
  {
    $this->db->query("SELECT * FROM emc_categories WHERE emc_categories_id_eca > 0 ORDER BY name_eca ASC");
    $categories = $this->db->loadAssocList(); 
    $ret = array();
    foreach($categories as $c => $category)
    {
      $ret[$category['id_eca']] = $category['name_eca'];
    }
    return $ret;
  }

  private function createOpeArray($operators)
  {
    $opes = array();
    foreach($operators as $o => $operator)
    {
      $opes[$operator['code_eo']] = $operator;
    }
    return $opes;
  }

  /**
   * Services getter (for France), called when we show the services list on the configuration page.
   * @return array List of services.
   */
  private function getServicesFr()
  {
    //if(count($_SESSION['servicesFr']) == 0)
    //{
      $this->db->query("SELECT es.*, eo.* FROM emc_services es
      JOIN emc_operators eo ON eo.code_eo = es.emc_operators_code_eo
      WHERE es.zones_es != 2 ORDER BY es.id_es ASC");
      $services = $this->db->loadAssocList();
      foreach($services as $s => $service)
      { 
        $ret[$service['emc_operators_code_eo'].$service['code_es']] = array('name' => $service['label_es'].' (<b>'.$service['name_eo'].'</b>)');
      }
      $_SESSION['servicesFr'] = $ret;
    //}
    return $_SESSION['servicesFr'];
  }

  /**
   * Services getter (for international), called when we show the services list on the configuration page.
   * @return array List of services.
   */
  private function getServicesInt()
  {
    //if(count($_SESSION['servicesInt']) == 0)
    //{
      $this->db->query("SELECT es.*, eo.* FROM emc_services es
      JOIN emc_operators eo ON eo.code_eo = es.emc_operators_code_eo
      WHERE es.zones_es > 1 ORDER BY es.id_es ASC");
      $services = $this->db->loadAssocList();
      foreach($services as $s => $service)
      { 
        $ret[$service['emc_operators_code_eo'].$service['code_es']] = array('name' => $service['label_es'].' (<b>'.$service['name_eo'].'</b>)');
      }
      $_SESSION['servicesInt'] = $ret;
    //}
    return $_SESSION['servicesInt'];
  }

  /** 
   * Getter used to display a select with delays.
   * @access private
   * @return array
   */
  private function getDelays()
  {
    return $this->_delays;
  }

  /** 
   * Getter to parcel points openers.
   * @access private
   * @return array
   */
  private function getOpeners()
  {
    return $this->_openers;
  }

  /** 
   * Getter used to display a select with delays.
   * @access private
   * @return array
   */
  private function getTypes()
  {
    return $this->_types;
  }

  /** 
   * Getter used to display the environments used by API.
   * @access private
   * @return array
   */
  private function getEnvs()
  {
    return $this->_envs;
  }

  /** 
   * Getter host by defined environment.
   * @access public
   * @return array
   */
  public function getHost($key)
  {
    return $this->_host[$key];
  }

  /** 
   * Getter used to reasons for foreign country shipping (and pro forma).
   * @access private
   * @return array
   */
  private function getenvoi_raison()
  {
    require_once(CLASSPATH ."shipping/envoimoinscher/WebService.php");
    require_once(CLASSPATH ."shipping/envoimoinscher/Quotation.php");
    $cotCl = new Env_Quotation(array());
    return $cotCl->getReasons($this->_reasTransl);
  }

  /** 
   * Getter used only to "respect" the standards.
   * @access private
   * @return void
   */
  private function getdepot_pointrelais()
  {
  }

  /** 
   * Getter used to display a select with start of disponibilites for shipping.
   * @access private
   * @return array
   */
  private function getDispoStart()
  {
    return $this->_hourStart;
  }

  /** 
   * Getter used to display a select with start of disponibilities for shipping.
   * @access private
   * @return array
   */
  private function getdisponibilite_HDE()
  {
    return $this->getDispoStart();
  }

  /** 
   * Getter used to display a select with end of disponibilities for shipping.
   * @access private
   * @return array
   */
  private function getDispoEnd()
  {
    return $this->_hourEnd;
  }

  /** 
   * Getter used to display a select with end of disponibilities for shipping.
   * @access private
   * @return array
   */
  private function getdisponibilite_HLE()
  {
    return $this->getDispoEnd();
  }
 
  private function getVoid()
  {
    return '';
  }

  private function setDate($from, $days, $format = 'Y-m-d H:i:s')
  {
    $time = strtotime($from);
    return date($format, ($time + $days));
  }

  private function prepareOrderInfo($orderId)
  { 
    $query = "SELECT o.*, ep.*, ui.*, oi.order_item_name, oi.product_final_price,  oi.product_quantity , p.product_weight, u.email AS userEmail, c.country_2_code 
    FROM #__{vm}_orders o
    LEFT JOIN emc_points ep ON ep.order_id = o.order_id
    JOIN #__{vm}_user_info ui ON ui.user_info_id = o.user_info_id
    JOIN #__users u ON u.id = o.user_id
    JOIN #__{vm}_country c ON c.country_3_code = ui.country
    JOIN #__{vm}_order_item oi ON oi.order_id = o.order_id
    JOIN #__{vm}_product p ON p.product_id = oi.product_id
    WHERE o.order_id = ".$orderId."";
    $this->db->query($query);
    $order = $this->db->loadAssocList();
    // prepare package content and package description
    $items = array();
    $i = 1;
    $package = array();
    foreach($order as $data)
    {
      // $qDim = "SELECT length_ed, width_ed, height_ed FROM emc_dimensions WHERE weight_from_ed < ".(float)$data['product_weight']." AND 
      // weight_ed >= ".(float)$data['product_weight']." ";
      // $this->db->query($qDim);
      // $dimensions = $this->db->loadAssocList();
      $totalWeight += ($data['product_quantity']*$data['product_weight']);
      $items[] = $data['order_item_name'];
      // $package[$i] = array('poids' => ($data['product_quantity']*$data['product_weight'])/*, 'longueur' => $dimensions[0]['length_ed'], 'largeur' => $dimensions[0]['width_ed'], 'hauteur' => $dimensions[0]['height_ed']*/);
      // $i++;
    } 
    $qDim = "SELECT length_ed, width_ed, height_ed FROM emc_dimensions WHERE weight_from_ed < ".(float)$totalWeight." AND 
    weight_ed >= ".(float)$totalWeight." ";
    $this->db->query($qDim);
    $dimensions = $this->db->loadAssocList();
    $package[1] = array('poids' => $totalWeight, 'longueur' => $dimensions[0]['length_ed'], 'largeur' => $dimensions[0]['width_ed'], 'hauteur' => $dimensions[0]['height_ed']);

    // prepare delivery address
    define('colis_description', implode(', ' , $items));
    $delAddress = $order[0]['address_1'];
    if($order[0]['address_2'] != '')
    {
      $delAddress .= '|'.$order[0]['address_2'];
    }
    $data['delivery'] = array('country' => $order[0]['country_2_code'], 'first_name' => $order[0]['first_name'], 'last_name' => $order[0]['last_name'], 
    'zip' => $order[0]['zip'], 'city' => $order[0]['city'], 'phone_1' => $order[0]['phone_1'], 'email' => $order[0]['userEmail'],
    'address' => $delAddress);
    // France metropolitan case : ISO code is FX instead of FR
    if($data['delivery']['country'] == 'FX' || $data['delivery']['country'] == 'FXX')
    {
      $data['delivery']['country'] = 'FR';
    }
    // shippment method codes
    $method = explode('|', $order[0]['ship_method_id']);
    $this->db->setQuery("SELECT * FROM emc_services es JOIN emc_operators eo ON es.emc_operators_code_eo = eo.code_eo 
    WHERE es.code_es = '".trim($method[2])."' AND (eo.code_eo = '".trim($method[1])."' OR eo.name_eo LIKE '%".trim($method[1])."%') ");
    $row = $this->db->loadAssocList();
    $method = array(0 => '', 1 => $row[0]['code_eo'], 2 => $row[0]['code_es'], 3 => $method[3], 4 => $method[4]);

    // order informations
    $data['order'] = array('order_subtotal' => $order[0]['order_subtotal']);
    // if foreign delivery address, make proforma
    if($data['delivery']['country'] != 'FR')
    {
      // $package[1]['poids'] = $package[1]['poids'] + 0.1;
      $proformaData = $this->makeProforma($order);
    }
    return array_merge($data, array('package' => $package, 'method' => $method, 'proforma' => $proformaData, 'parcelPoint' => $order[0]['point_ep']));
  }

  private function insertEmcOrder($orderId, $emcData, $post)
  {
    // insert new emc order into emc_orders 
   $this->db->setQuery('INSERT INTO emc_orders (order_id, date_eo, price_ttc_eo, price_ht_eo, operator_eo, service_eo,
   ref_eo, date_collect_eo, date_del_eo, code_eo) 
   VALUES ('.$orderId.', "'.date('Y-m-d H:i:s').'", "'.$emcData['price']['tax-inclusive'].'", "'.$emcData['price']['tax-exclusive'].'", 
   "'.$emcData['offer']['operator']['code'].'", "'.$emcData['service']['label'].'", "'.$emcData['ref'].'", 
   "'.$emcData['collection']['date'].' '.$emcData['collection']['time'].'", "'.$emcData['delivery']['date'].' '.$emcData['delivery']['time'].'",
   "'.$post['codeOrder'].'")');
   $this->db->query();

    // insert shipping documents into emc_documents : first labels, after proforma (if exists)
    foreach($emcData['labels'] as $label)
    {
      $this->db->setQuery('INSERT INTO emc_documents (order_id, link_ed, type_ed) VALUES 
      ('.$orderId.', "'.$label.'", "label")');
      $this->db->query();
    }
 
    if($emcData['proforma'] != '')
    {
      $this->db->setQuery('INSERT INTO emc_documents (order_id, link_ed, type_ed) VALUES 
      ('.$orderId.', "'.$label.'", "proforma")');
      $this->db->query();
    }

    // change VirtueMart order state
    $this->db->setQuery('UPDATE #__{vm}_orders SET order_status = "S" WHERE order_id = '.$orderId.' ');
    $this->db->query();

    if($post['retrait_pointrelais'] != '')
    {
      $this->db->setQuery('UPDATE emc_points SET point_ep = "'.$emcData['offer']['operator']['code'].'-'.$post['retrait_pointrelais'].'" WHERE order_id = '.$orderId.' ');
      $this->db->query();
    }

    // insert into labels table
    $this->db->setQuery('INSERT INTO #__{vm}_shipping_label (order_id, shipper_class, tracking_number, label_is_generated )
    VALUES ("'.$orderId.'", "envoimoinscher", "'.$emcData['ref'].'", 1)');
    $this->db->query();
  }

  private function makeProforma($items)
  {
    $s = 1;
    foreach($items as $item)
    {
      $proforma[$s] = array('description_en' => translateGoogle($item['order_item_name']),
      'description_fr' => $item['order_item_name'],'nombre' => $item['product_quantity'],  'valeur' => (float)($item['product_quantity']*$item['product_final_price']), 
      'origine' => "FR", 'poids' => ($item['product_weight'] - 0.1) );
      $s++;
    }
    return $proforma;
  }

  private function backendStyles($styles = array(), $showHeader = true) 
  { 
?> 
<style type="text/css"> 
.formEmc p {clear:both; margin:10px 0 15px 0;}
.formEmc p label {width:150px; float:left; margin-right:5px; text-align:right;}
table.formEmc {border-collapse: collapse;}
table.formEmc td {border: 1px solid #000000;}
table.formEmc thead td {border-bottom: 1px solid #000000;}
.big {font-size:20px;}
.multiCheckbox li {width:150px; margin-right:10px; float:left; list-style:none; } 
.band {width:100%; background: #FFFFFF; padding:5px 0; font-size:13px; font-weight:bold;
border-top: 1px solid #000000; border-bottom:1px solid #000000;}
.blockHelp {width:500px; padding:10px; border:1px solid #000000; background: #FFFFFF;}
.trackTable {border-collapse: collapse;}
.trackTable td {border:1px solid #000000;}
.trackTable thead td {background: #d2d2d2; padding:5px;}
.trackTable tbody td {padding:5px;}
</style>
<?php if($showHeader) { ?>
<p class="band">
<?php if(!defined("emcIsInstalled")) {
?>
<a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=install" style="<?php echo $styles['install'];?>">installer</a>
<?php } else { 
$majCss = 'style="display:none;"';
$baseDir = CLASSPATH.'/shipping/emc_update';
if(count(scandir(CLASSPATH.'/shipping/emc_update')) > 2)
{
  $majCss = '';
} ?>
<a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart" style="<?php echo $styles['config'];?>">configuration</a> |
<a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=table&limit=50&limitstart=0" style="<?php echo $styles['cmd'];?>">expéditions</a>
<span <?php echo $majCss;?>>| <a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=update" style="<?php echo $styles['update'];?>">mises à jour</a> </span>
<!-- | <a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=uninstall" style="<?php echo $styles['uninstall'];?>">désinstaller</a>-->
<?php } ?>
</p>
<?php } ?>
<?php
  }

  public function __toString()
  {
    return 'envoimoinscher';
  }

  /** 
   * Shipping labels part : 
   * It can't convert PDF to JPG. It's why user is redirected to EnvoiMoinsCher for download his shipping
   * label.
   */ 
  public function generate_label() 
  {
    // get label from database 
    $orderId = (int)$_GET['order_id'];
    $query = "SELECT * FROM emc_documents WHERE order_id = ".$orderId." AND type_ed = 'label' ";
    $this->db->query($query);
    $label = $this->db->loadAssocList(); 
    // make JavaScript redirection to show an EnvoiMoinsCher PDF
    echo '<script type="text/javascript">
      document.location = "'.$label[0]['link_ed'].'";
    </script>';
  }
  // These methods are called by order.label_print.php
  public function get_label_image() {}
  public function get_label_dimensions() {}
  public function get_label_image_type() {}

  /**
   * Tracking function.
   * @param int $orderId Order id.
   * @param string $from Indicates the source of call. Back => backend, front => frontend and a supplementary
   * condition.
   */
  public function track($orderId, $from = 'back') 
  {
    $wherePlus = '';
    if($from == 'front')
    {
      $wherePlus = 'AND o.user_id = '.(int)$_SESSION['auth']["user_id"].'';
    }
    $this->backendStyles(array(), false);
    $query = "SELECT ui.first_name, ui.last_name, et.*, DATE_FORMAT(et.date_et, '%d-%m-%Y') AS date FROM emc_tracking et 
    JOIN #__{vm}_orders o ON o.order_id = et.order_id
    JOIN #__{vm}_user_info ui ON ui.user_info_id = o.user_info_id
    WHERE et.order_id = ".$orderId." ".$wherePlus." ORDER BY et.id_et DESC";
    $this->db->query($query);
    $trackInfos = $this->db->loadAssocList();
    if(count($trackInfos) > 0)
    {
?>
    <p><b>Numéro de la commande : </b> <?php echo sprintf("%08d", $trackInfos[0]["order_id"]);?> </p>
    <p><b>Destinataire : </b> <?php echo $trackInfos[0]["first_name"]; ?> <?php echo $trackInfos[0]["last_name"]; ?></p>
    <table class="trackTable"> 
      <thead>
        <tr><td>Date</td><td>Informations</td><td>Localisation</td></tr>
      </thead>
      <tbody>
<?php
    foreach($trackInfos as $t => $track)
    {
?>
      <tr><td><?php echo $track['date'];?></td><td><?php echo $this->_states[$track['state_et']];?><br /><?php echo $track['text_et'];?></td><td><?php echo $track['localisation_et'];?></td></tr>
<?php
    }
?>
    </tbody></table>
<?php
    }
    else {
?>
    <p>Il n'y a pas d'informations de suivi pour cette commande</p>
<?php
    } 
  }
  
  /**
   * Installs module.
   * @access public
   * @return void
   */
  public function install()
  {
    $queries = explode('-- sql_query', file_get_contents(dirname(__FILE__).'/envoimoinscher.sql'));
    foreach($queries as $q => $query)
    {
      $this->db->query($query);
    }
    $this->db->query("INSERT INTO #__{vm}_module (module_name, module_description, module_perms, module_publish, list_order)
    VALUES 
    ('emc_parcelpoints', 'Handle parcel points.', 'none', 'Y', 11111),
    ('emc_tracking', 'Handle tracking.', 'none', 'Y', 111111)");
    // alter carrier table 
    $this->db->query("ALTER TABLE #__{vm}_shipping_carrier ADD is_emc INT(1) NOT NULL");
    $this->db->query("ALTER TABLE #__{vm}_shipping_carrier ADD emc_code VARCHAR(30) NOT NULL");
    file_put_contents(CLASSPATH.'shipping/envoimoinscher.cfg.php', '<?php define("emcIsInstalled", 1); ?>');
    $_SESSION['installOk'] = 1;
    Header("Location: index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart");
    die();
  }

  /**
   * Uninstalls module (only database data, remove all data [orders, configurations, dimensions...]).
   * @access public
   * @return void
   */
  public function uninstall()
  {
    if($_GET['do'] == 1)
    {
      foreach($this->_tables as $t => $table)
      {
        $this->db->query("DROP TABLE ".$table."");
      }
	  file_put_contents(CLASSPATH.'shipping/envoimoinscher.cfg.php', ''); 
      Header("Location: index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=uninstall&do=2");
    }
    elseif($_GET['do'] == 2)
    {
?>
    <p><b>Le module a été correctement désinstallé.</b></p>
<?php
    }
    else
    {
?>
    <p><b>Etes-vous sûr de vouloir désinstaller le module ? Les commandes, les bordereaux et les données de configuration
    seront supprimés.</b></p>
    - <a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=uninstall&do=1">Oui, je veux désinstaller le module</a>
    <br />- <a href="index.php?page=store.shipping_module_form&shipping_module=envoimoinscher.php&option=com_virtuemart&act=table&limit=50&limitstart=0">Non, je ne veux pas le désintaller</a>
<?php
    }
  }

  /**
   * Updates module. Firstly it gets update files from emc_update repository. After it executes the update commands.
   * @access public
   * @return void
   */
  public function update()
  {
    $baseDir = CLASSPATH.'/shipping/emc_update';
    $files = scandir($baseDir);
    foreach($files as $f => $file)
    {
      if($file != '.' && $file != '..')
      {
        $queries = explode('-- sql_query', file_get_contents($baseDir.'/'.$file));
        foreach($queries as $q => $query)
        {
          $this->db->query($query);
        }
        // If update method exists, call it
        $function = str_replace('.', '_', str_replace('.sql', '', $file));
        if(method_exists($this, $function))
        {
          $this->$function();
        }
        // Remove update file
        unlink($baseDir.'/'.$file);
      }
    }
?>
    La mise à jour a été correctement exécutée.
<?php
  }

  /**
   * Upgrades from 1.0.1 to 1.0.2 : 
   * - column emc_name added
   * - column emc_name filled up with shipping_carrier_name value (only for is_emc = 1)
   * @access private
   * @return void
   */
  private function upgrade_1_0_1_1_0_2()
  {
    $query = "SELECT shipping_carrier_name, shipping_carrier_id FROM #__{vm}_shipping_carrier
    WHERE is_emc = 1";
    $this->db->query($query);
    $carriers = $this->db->loadAssocList();
    foreach($carriers as $c => $carrier)
    {
      $this->db->setQuery('UPDATE #__{vm}_shipping_carrier 
      SET emc_name = "'.$carrier['shipping_carrier_name'].'" 
      WHERE shipping_carrier_id = '.$carrier['shipping_carrier_id'].' ');
      $this->db->query();
    }
  }

}

  function make_multi_checkbox($name, $items, $default, $value)
  {
    $valueArray = explode(',', $value);
    $return = '<table class="multiCheckbox"><tr>';
    $c = 0;
    foreach($items as $i => $item)
    {
      if($c == 4)
      {
        $return .= '</tr><tr>';
        $c = 0;
      }
      $checked = '';
      if(in_array($i, $valueArray))
      {
        $checked = 'checked="checked"';
      }
      $return .= '<td><input type="checkbox" name="'.$name.'[]" id="'.$name.'_'.$i.'" value="'.$i.'" '.$checked.' /><label for="'.$name.'_'.$i.'">'.$item['name'].'</label></td>';
      $c++;
    }
    return $return.'</tr></table>';
  }

  function make_select($name, $items, $default, $value)
  {
    $select = '<select name="'.$name.'">';
    foreach($items as $i => $item)
    {
      $selected = '';
      if($value == $i || ($value == '' && $default == $i))
      {
        $selected = 'selected="selected"';
      }
      $select .= '<option value="'.$i.'" '.$selected.'>&nbsp;'.$item.'&nbsp;</option>';
    }
    $select .= '</select>';
    return $select;
  } 
  function make_textarea($name, $src, $default, $value)
  {
    if($value == '')
    {
      $value = $default;
    }
    return '<textarea name="'.$name.'" id="'.$name.'">'.$value.'</textarea>';
  }

  function translateGoogle($text)
  {
    header("Content-Type: text/html;charset=utf-8");
    $data = file_get_contents("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($text)."&langpair=fr|en");
    $data = json_decode($data);
    if((int)$data->responseStatus == 200)
    {
      return $data->responseData->translatedText;
    }
    else 
    {
      return $text;
    }
  }

  function makeMap($points, $showLink)
  {
    if($showLink)
    {
      $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
      $old = array('http://', 'https://');
      $new = array('', '');
      $siteUrl = $protocol.''.str_replace($old, $new, JURI::base());
      $pointsHTML = '<a href="'.$siteUrl.'/index.php?page=emc_parcelpoints.list&option=com_virtuemart&points='.$points.'" id="loadPointsa" onclick="showPr(\'loadPoints\', this); return false;">sélectionnez votre point de proximité</a>
      <span id="loadPoints" style="display:none;"><br /><img src="'.$siteUrl.'images/emc_loader.gif" />  Chargement des points de proximité...</span>';
    } 

    // 0 => open parcel point in the same page, 1 => open parcel points in the new window
    if((int)popup == 0)
    {
      $showPrMethod = 'function showPr(block, el) 
      { 
        // append mapContainer at the end of the body tag (to avoid positions problem)
        var contentMap = document.getElementById("mapToCopy").innerHTML;
        document.getElementById("mapToCopy").innerHTML = ""; 
        var ne = document.createElement("div");
        document.body.appendChild(ne);
        ne.innerHTML = contentMap;

        var offset = $("loadPointsa").getPosition();
        var newOffset = offset.y - 40;
        document.getElementById("mapContainer").style.top = newOffset+"px";
        document.getElementById(block).style.display = \'block\';
        document.getElementById("loadPointsa").style.display = "none";  
        new Ajax(document.getElementById("loadPointsa").href, {
          method : "get",
          onSuccess : function(responseText, responseXML) {
            document.getElementById("pointsList").innerHTML = responseText;
            document.getElementById("loadPoints").style.display = "none";
          }
        }).request();	
        opened = 0;
        map = null;
        geocoder = null;
        infowindow = new google.maps.InfoWindow();
        infoParcel = new Array();
        document.getElementById("map_canvas").innerHTML = "";		
      }';      
    }
    elseif((int)popup == 1 && $showLink)
    {
      $showPrMethod = '
      function putParcelPoint(parcelPoint, parcelName) 
      {
        window.parent.document.getElementById("point").value = parcelPoint;
        window.parent.document.getElementById("pointChoosen").innerHTML = parcelName;
      }
      function showPr(block, el) 
      { 
        window.open(document.getElementById("loadPointsa").href+"&popup=1","emcwindow","scrollbars=1, resizable=1,width=850,height=780");
      }';
      $addedHTML = '<input type="hidden" name="point" id="point" value="" /><p>Point sélectionné : <span id="pointChoosen"></span></p>';
    }
    return $pointsHTML.$addedHTML.'<div id="pointsList"></div>
          <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
          <div id="mapToCopy"><div id="mapContainer" style="display:none; width:80%; height:384px; background: #FFFFFF; position: absolute; z-index: 1111; top: 100px; left: 10%; border:3px solid #000000;">
          <p style="width:98%; text-align:right; padding-right:10px; margin-top:4px;"><a href="#" onclick="hideMap(); return false;">fermer X</a></p>
          <div id="map_canvas" style="width: 100%;height:350px;"></div></div></div>  

          <script type="text/javascript">

          var opened = 0;
          var geocoder;
          var map; 
          var marker; 
          var infowindow = new google.maps.InfoWindow();
          var points; 
          var infos;
          var parcelNames; 
          var parcelIds; 
          var j = 0; 
          var infoParcel = new Array();
 
          '.$showPrMethod.'

          function makeMap()
          { 
            if(opened == 1)
            {
              showMap();
            }
            else 
            { 
              initialize();
              opened = 1;
            }
          } 

          function initialize() 
          {     
            geocoder = new google.maps.Geocoder(); 
            var myOptions = {
              zoom: 13, 
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            points = document.getElementById("parcelPoints").value.split("|");
            infos = document.getElementById("parcelInfos").value.split("|");
            parcelNames = document.getElementById("parcelNames").value.split("|");
            parcelIds = document.getElementById("parcelIds").value.split("|");
            for(var i = 0; i < points.length; i++)
            {
              var address = points[i];
              infoParcel[i] = "<b>"+parcelNames[i]+"</b>" + "<br /><span onclick=\"javascript:selectPr(\'"+parcelIds[i]+"\'); return false;\" style=\"color: #135CAE; cursor: pointer;\">Sélectionner ce point</span> <br />"  + address + "<br />" + infos[i]; 
              if(geocoder)
              {
                geocoder.geocode({"address": address}, function(results, status) {
                  if(status == google.maps.GeocoderStatus.OK) 
                  {
                    makeMarker(j, results[0].geometry.location);
                    j++; 
                  }  
                }); 
              }   
            } 
            document.getElementById("mapContainer").style.display = "block"; 
          } 

          function makeMarker(s, location)
          { 
            map.setCenter(location);
            var marker = new google.maps.Marker({
              map: map, 
              position: location,
              title : ""+parcelNames[s]
            });
            marker.set("bulkContent", infoParcel[s]);
            google.maps.event.addListener(marker,"click",function(){
              infowindow.setContent(this.get("bulkContent"));
              infowindow.open(map,marker);
            });
          }

          function showMap()
          {
            document.getElementById("mapContainer").style.display = "block"; 
          }

          function hideMap()
          {
            document.getElementById("mapContainer").style.display = "none"; 
          }

          function selectPr(pr)
          {
            document.getElementById(relaisColisId).checked = true; 
            document.getElementById(pr).checked = true;
            hideMap();
          }
          </script>';

  } 

?>